﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PocketPond.Core;
using PocketPond.Core.Types;
using PocketPond.PondConsumer;
using Microsoft.WindowsMobile.Forms;

namespace PocketPond
{
    public partial class PostEvent : Form
    {
        Boolean bTwitter = false;
        Boolean bFacebook = false;
        Boolean bFlickr = false;
        Boolean bSapoFotos = false;

        int iTxtSize = 0;

        delegate void setStatus(String status);
        setStatus statusDelegate;

        Event _original = null;

        public PostEvent(Event ev)
        {
            _original = ev;

            init();

            switch (_original.ServiceId)
            {
                case Services.Twitter:
                    picTwitter.Visible = true;
                    picTwitter_Click(null, null);
                    txtText.Text = "@" + _original.AuthorScreenName + " ";
                    txtText.SelectionStart = txtText.TextLength;
                    break;
                case Services.Facebook:
                    picFacebook.Visible = true;
                    picFacebook_Click(null, null);
                    break;
            }
        }

        public PostEvent()
        {
            init();

            foreach (Account acc in PocketPond.Accounts.Values)
            {
                switch (acc.ServiceId)
                {
                    case Services.Twitter:
                        picTwitter.Visible = true;
                        picTwitter_Click(null, null);
                        break;
                    case Services.Facebook:
                        picFacebook.Visible = true;
                        picFacebook_Click(null, null);
                        break;
                    case Services.Flickr:
                        picFlickr.Visible = true;
                        picFlickr_Click(null, null);
                        break;
                    case Services.SapoFotos:
                        picSapoFotos.Visible = true;
                        picSapoFotos_Click(null, null);
                        break;
                }
            }
        }

        private void init()
        {
            InitializeComponent();

            txtText.Height = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height - txtText.Location.Y - 23;
            iTxtSize = txtText.Height;

            picTwitter.Image = imgs.Images[0];
            picFacebook.Image = imgs.Images[3];
            picFlickr.Image = imgs.Images[5];
            picSapoFotos.Image = imgs.Images[7];
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        Status status = new Status();
        String postMsg;
        private void menuItem1_Click(object sender, EventArgs e)
        {
            statusDelegate = new setStatus(status.setStatus);
            postMsg = txtText.Text;
            //System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(performPost));
            //th.Start();
            // TODO look at System.Threading.AutoResetEvent

            Cursor.Current = Cursors.WaitCursor;
            performPost();
            Cursor.Current = Cursors.Default;
            this.Close();
        }

        private void performPost()
        {
            Boolean bResult = false;
            String fileToken = null;
            String imgUrl = null;
            String longText = postMsg;
            String shortText;
            if (longText.Length > 140)
            {
                shortText = longText.Substring(0, 139);
            }
            else
            {
                shortText = longText;
            }

            if (_imageFile != null)
            {
                Invoke( statusDelegate, new object[] {"Posting to Flickr"});
                fileToken = PondRequest.uploadImage(ClientSettings.AuthToken, _imageFile);
                if (PocketPond.Accounts.ContainsKey(Services.Flickr) && bFlickr)
                {
                    Account acc = PocketPond.Accounts[Services.Flickr];
                    bResult = postOrReply(ClientSettings.AuthToken,
                                                   acc.AccountId,
                                                   shortText,
                                                   longText,
                                                   fileToken,
                                                   out imgUrl);
                    if (!bResult)
                    {
                        MessageBox.Show("Post to (" + acc.ServiceId.ToString() + ")" + acc.Description + " failed!");
                    }
                }

                if (PocketPond.Accounts.ContainsKey(Services.SapoFotos) && bSapoFotos)
                {
                    Invoke(statusDelegate, new object[] { "Posting to Sapo Fotos" });
                    Account acc = PocketPond.Accounts[Services.SapoFotos];
                    bResult = postOrReply(ClientSettings.AuthToken,
                                                   acc.AccountId,
                                                   shortText,
                                                   longText,
                                                   fileToken,
                                                   out imgUrl);
                    if (!bResult)
                    {
                        MessageBox.Show("Post to (" + acc.ServiceId.ToString() + ")" + acc.Description + " failed!");
                    }
                }
            }

            if (PocketPond.Accounts.ContainsKey(Services.Twitter) && bTwitter)
            {
                Invoke(statusDelegate, new object[] { "Posting to Twitter" });
                String newShort = shortText;
                if (imgUrl != null)
                {
                    newShort += " " + imgUrl;
                }
                Account acc = PocketPond.Accounts[Services.Twitter];
                bResult = postOrReply(ClientSettings.AuthToken,
                                               acc.AccountId,
                                               newShort,
                                               string.Empty);
                if (!bResult)
                {
                    MessageBox.Show("Post to (" + acc.ServiceId.ToString() + ")" + acc.Description + " failed!");
                }
            }

            if (PocketPond.Accounts.ContainsKey(Services.Facebook) && bFacebook)
            {
                Invoke(statusDelegate, new object[] { "Posting to Facebook" });
                Account acc = PocketPond.Accounts[Services.Facebook];
                bResult = postOrReply(ClientSettings.AuthToken,
                                               acc.AccountId,
                                               shortText,
                                               longText,
                                               fileToken,
                                               out imgUrl);
                if (!bResult)
                {
                    MessageBox.Show("Post to (" + acc.ServiceId.ToString() + ")" + acc.Description + " failed!");
                }
            }
        }

        bool postOrReply(String authToken, String accountId, String smallText,
                         String largeText)
        {
            String dummy;
            return postOrReply(authToken, accountId, smallText, largeText, null, out dummy);
        }

        bool postOrReply(String authToken, String accountId, String smallText,
                         String largeText, String fileToken)
        {
            String dummy;
            return postOrReply(authToken, accountId, smallText, largeText, fileToken, out dummy);
        }

        bool postOrReply( String authToken, String accountId, String smallText, 
                          String largeText, String fileToken, out String punyUrl)
        {
            if (_original == null)
            {
                return PondRequest.sendPost(authToken, accountId, smallText,
                                            largeText, fileToken, out  punyUrl);
            }
            else
            {
                return PondRequest.sendReply(authToken, accountId, smallText,
                                            largeText, fileToken, _original.EventId, out punyUrl);
            }
        }

        private void picFacebook_Click(object sender, EventArgs e)
        {
            bFacebook = !bFacebook;
            if (bFacebook)
            {
                picFacebook.Image = imgs.Images[2];
            }
            else
            {
                picFacebook.Image = imgs.Images[3];
            }
        }

        private void picTwitter_Click(object sender, EventArgs e)
        {
            bTwitter = !bTwitter;
            if (bTwitter)
            {
                picTwitter.Image = imgs.Images[0];
            }
            else
            {
                picTwitter.Image = imgs.Images[1];
            }
        }

        private void picFlickr_Click(object sender, EventArgs e)
        {
            bFlickr = !bFlickr;
            if (bFlickr)
            {
                picFlickr.Image = imgs.Images[4];
            }
            else
            {
                picFlickr.Image = imgs.Images[5];
            }
        }

        private void picSapoFotos_Click(object sender, EventArgs e)
        {
            bSapoFotos = !bSapoFotos;
            if (bSapoFotos)
            {
                picSapoFotos.Image = imgs.Images[6];
            }
            else
            {
                picSapoFotos.Image = imgs.Images[7];
            }
        }

        private String _imageFile = null;
        private Boolean bImageWait = false;

        private void picFile_Click(object sender, EventArgs e)
        {
            if (!bImageWait)
            {
                bImageWait = true;
                SelectPictureDialog dlg = new SelectPictureDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    _imageFile = dlg.FileName;
                    Bitmap img = new Bitmap(_imageFile);
                    picFile.Image = img;
                }
                bImageWait = false;
            }
        }

        private void picCamera_Click(object sender, EventArgs e)
        {
            if (!bImageWait)
            {
                bImageWait = true;
                CameraCaptureDialog dlg = new CameraCaptureDialog();
                dlg.Resolution = new Size(640, 480);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    _imageFile = dlg.FileName;
                    Bitmap img = new Bitmap(_imageFile);
                    picFile.Image = img;
                }
                bImageWait = false;
            }
        }

        private void PostEvent_Closed(object sender, EventArgs e)
        {
            ControlHelper.DetachGotLostFocusEvents(
                    this.Controls,
                    new EventHandler(EditControl_GotFocus),
                    new EventHandler(EditControl_LostFocus));
        }

        private void EditControl_GotFocus(object sender, EventArgs e)
        {
            inputPanel1.Enabled = true;
        }

        private void EditControl_LostFocus(object sender, EventArgs e)
        {
            inputPanel1.Enabled = false;
        }

        private void PostEvent_Load(object sender, EventArgs e)
        {
            ControlHelper.AttachGotLostFocusEvents(
                this.Controls,
                new EventHandler(EditControl_GotFocus),
                new EventHandler(EditControl_LostFocus));
        }

        private void PostEvent_Closing(object sender, CancelEventArgs e)
        {
            inputPanel1.Enabled = false;
        }

        private void inputPanel1_EnabledChanged(object sender, EventArgs e)
        {
            if (inputPanel1.Enabled)
            {
                txtText.Height = inputPanel1.VisibleDesktop.Height - txtText.Location.Y + 17;
            }
            else
            {
                txtText.Height = inputPanel1.VisibleDesktop.Height - txtText.Location.Y - 24;
            }
        }

        private void txtText_TextChanged(object sender, EventArgs e)
        {
            lblCounter.Text = txtText.TextLength + "/140";
        }
    }
}